package com.itany;

import com.google.gson.Gson;
import com.itany.entity.ChatRequest;
import com.itany.entity.ChatResponse;
import com.itany.entity.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;

@Component
public class DeepSeekChat {
    @Value("${deepseek.url}")//读取application。properties配置文件
    String deepseekURI;
    @Value("${deepseek.key}")
    String deepseekKEY;
    //发送
    public String sendRequest(ChatRequest requestBody){
        //客户端
        HttpClient client=HttpClient.newHttpClient();
        //保存json对象
        Gson gson= new Gson();
        String requestBodyJson=gson.toJson(requestBody); //"[{“k1”:“v1”,“k2”:“V2”}]"
        //构造请求对象，指定请求头中的内容以及身份验证
        //http协议支持发送request
        HttpRequest request=HttpRequest.newBuilder()
                .uri(URI.create(deepseekURI))
                .header("Content-Type","application/json")
                .header("Authorization","Bearer "+deepseekKEY)
                .POST(HttpRequest.BodyPublishers.ofString(requestBodyJson))
                .build();
        System.out.println("----------已提交----,正在思考....");
        HttpResponse<String> httpResponse=null;
        try {
            //http中的响应结构体
            httpResponse=client.send(request, HttpResponse.BodyHandlers.ofString());
            if(httpResponse.statusCode()==200){
                //正确响应
                //http响应结构转换为deepseek的结构
                ChatResponse chatResponse= gson.fromJson(httpResponse.body(), ChatResponse.class);
                return chatResponse.getChoices().get(0).getMessage().getContent();
            }else{
                return "请求失败·状态码："+httpResponse.statusCode()+"\n"
                        +"响应："+httpResponse.body();
            }

        }catch(Exception e) {
            return "请求异常："+e.getMessage();
        }

    }

    public  void ask(String centent) {
        List<Message> messages=new ArrayList<>();
        messages.add(new Message("user",centent));
       //构造请求体
        ChatRequest chatRequest=new ChatRequest(messages);
        System.out.println("-----正在提交问题");
        //发送请求

       String response= sendRequest(chatRequest);
        System.out.println("响应内容如下:");
        System.out.println(response);
    }

}
